import { ref, computed } from 'vue'
import permission from '@/utils/permission'
import { ElMessage } from 'element-plus'

/**
 * 权限管理组合式函数
 * 提供权限检查和403错误处理功能
 */
export function usePermission() {
  // 用户权限列表
  const userPermissions = ref([])
  
  // 加载权限状态
  const loadingPermissions = ref(false)

  /**
   * 初始化用户权限
   */
  const initPermissions = () => {
    try {
      const userInfo = localStorage.getItem('userInfo')
      if (userInfo) {
        const user = JSON.parse(userInfo)
        userPermissions.value = user.permissions || []
      }
    } catch (error) {
      console.error('初始化用户权限失败:', error)
      userPermissions.value = []
    }
  }

  /**
   * 检查是否有指定权限
   * @param {string} permissionCode - 权限代码
   * @returns {boolean} - 是否有权限
   */
  const hasPermission = (permissionCode) => {
    if (!permissionCode) return true
    return userPermissions.value.includes(permissionCode)
  }

  /**
   * 检查是否有任意一个权限
   * @param {Array} permissionCodes - 权限代码数组
   * @returns {boolean} - 是否有权限
   */
  const hasAnyPermission = (permissionCodes) => {
    if (!permissionCodes || permissionCodes.length === 0) return true
    return permissionCodes.some(code => hasPermission(code))
  }

  /**
   * 检查是否有所有权限
   * @param {Array} permissionCodes - 权限代码数组
   * @returns {boolean} - 是否有权限
   */
  const hasAllPermissions = (permissionCodes) => {
    if (!permissionCodes || permissionCodes.length === 0) return true
    return permissionCodes.every(code => hasPermission(code))
  }

  /**
   * 处理403权限不足错误
   * @param {Object} error - 错误对象
   * @param {Object} options - 配置选项
   */
  const handlePermissionDenied = (error, options = {}) => {
    permission.handlePermissionDenied(error, options)
  }

  /**
   * 显示权限不足提示
   * @param {string} operation - 操作名称
   */
  const showPermissionDeniedMessage = (operation = '执行此操作') => {
    permission.showPermissionDeniedMessage(operation)
  }

  /**
   * 权限不足时执行操作
   * @param {string} permissionCode - 权限代码
   * @param {Function} callback - 有权限时的回调函数
   * @param {Function} fallback - 无权限时的回调函数
   */
  const executeWithPermission = (permissionCode, callback, fallback = null) => {
    if (hasPermission(permissionCode)) {
      if (callback) callback()
    } else {
      if (fallback) {
        fallback()
      } else {
        showPermissionDeniedMessage()
      }
    }
  }

  /**
   * 创建权限检查的计算属性
   * @param {string} permissionCode - 权限代码
   * @returns {ComputedRef<boolean>} - 是否有权限
   */
  const createPermissionComputed = (permissionCode) => {
    return computed(() => hasPermission(permissionCode))
  }

  /**
   * 创建多个权限检查的计算属性
   * @param {Array} permissionCodes - 权限代码数组
   * @param {string} type - 检查类型 ('any' | 'all')
   * @returns {ComputedRef<boolean>} - 是否有权限
   */
  const createPermissionsComputed = (permissionCodes, type = 'any') => {
    return computed(() => {
      if (type === 'all') {
        return hasAllPermissions(permissionCodes)
      } else {
        return hasAnyPermission(permissionCodes)
      }
    })
  }

  /**
   * 刷新权限信息
   */
  const refreshPermissions = async () => {
    loadingPermissions.value = true
    try {
      // 这里可以调用API重新获取用户权限
      initPermissions()
    } catch (error) {
      console.error('刷新权限失败:', error)
      ElMessage.error('刷新权限失败')
    } finally {
      loadingPermissions.value = false
    }
  }

  // 初始化权限
  initPermissions()

  return {
    // 状态
    userPermissions,
    loadingPermissions,
    
    // 方法
    hasPermission,
    hasAnyPermission,
    hasAllPermissions,
    handlePermissionDenied,
    showPermissionDeniedMessage,
    executeWithPermission,
    createPermissionComputed,
    createPermissionsComputed,
    refreshPermissions,
    initPermissions
  }
} 